package cn.yunhe.realm;

import cn.yunhe.pojo.CurrentUser;
import cn.yunhe.pojo.ModuleP;
import cn.yunhe.pojo.Userp;
import cn.yunhe.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 获取用户
        CurrentUser currentUser = (CurrentUser) principalCollection.getPrimaryPrincipal();
        Userp user = currentUser.getUserP();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 填充用户权限
        List<ModuleP> modulePList = userService.getPermissionsByUserId(user.getUserId());
        if (modulePList != null && modulePList.size() > 0) {
            for (ModuleP m : modulePList) {
                authorizationInfo.addStringPermission(m.getCpermission());
            }
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取身份信息
        String username =  authenticationToken.getPrincipal().toString();
        //根据用户名查找用户信息
        Userp userP = userService.login(username);
        if(userP==null){
            // 如果没有查到用户  就抛出未知账号异常
            throw  new UnknownAccountException();
        }
        //根据用户信息查询用户扩展信息和部门信息
        CurrentUser currentUser = userService.findUserInfoDeptByUser(userP);

        String password = userP.getPassword();//获取密码
        String salt = userP.getUserName()+userP.getUserId();//根据用户名和编号作为盐值   admin002108e2-9a10-4510-9683-8d8fd1d374ef
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(currentUser,password, ByteSource.Util.bytes(salt),this.getName());
        return info;
    }

    //清空缓存:在权限修改后调用realm中的方法，realm已经由spring管理，所以从spring中获取realm实例，调用clearCached方法。
    public void clearCached() {
        //获取身份信息
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        //调用父类中清空缓存的方法
        super.clearCache(principals);
    }
}
